package com.template.cms.web.controller;

import javax.inject.Inject;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.template.cms.auth.service.IGroupService;
import com.template.cms.auth.service.IRoleService;
import com.template.cms.auth.service.IUserService;
import com.template.cms.web.dto.UserDto;

@Controller
@RequestMapping("/user")
public class UserController {
	
	@Inject
	private IUserService userService;
	
	@Inject
	private IRoleService roleService;
	
	@Inject
	private IGroupService groupService;
	
	private void initAddUser(Model model){
		model.addAttribute("roles", roleService.listRole());
		model.addAttribute("groups", groupService.listGroup());
	}
	
	@RequestMapping(value="/aaaa")
	public String userinfo(Model model){
		model.addAttribute("datas", userService.listUsers());
		return "user/list";
	}
	
	@RequestMapping(value="/add", method=RequestMethod.GET)
	public String add(Model model){
		model.addAttribute("userDto", new UserDto());
		initAddUser(model);
		System.out.println("add++++");
		return "user/add";
	}
	
	@RequestMapping(value = "/add", method = RequestMethod.POST)
	public String add(@Validated UserDto userDto, BindingResult br, Model model) {
		if (br.hasErrors()) {
			initAddUser(model);
			return "user/add";
		}
		userService.add(userDto.getUser(), userDto.getRoleIds(),
				userDto.getRoleIds());
		return "redirect:/user/userinfo";
	}
}
